import { useState, useEffect } from "react";

const useWakeApp = article => {
  const [appUrl, setAppUrl] = useState("");
  const [isIos, setIsIos] = useState("");
  let { articleType, articleId } = article;
  useEffect(() => {
    let UA = window.navigator.userAgent.toLowerCase();
    let isIos = (UA && /iphone|ipad|ipod|ios/.test(UA)) || false;
    let isAndroid = (UA && /(Android)/i.test(UA)) || false;

    articleId = !getQueryString("id") ? articleId : getQueryString("id");
    if (isIos) {
      let appUrl = `https://www.hndt.com/dowload/dxXw/index.html?id=${articleId}&msgType=${articleType}`;
      setAppUrl(appUrl);
      setIsIos("ios");
    } else if (isAndroid) {
      let appUrl = `https://a.app.qq.com/o/simple.jsp?pkgname=com.hnr.dxxw&android_schema=schemedxxw%3a%2f%2fhostdxxw%3a8080%2fpath?id=${articleId}%26msgType=${articleType}`;
      setAppUrl(appUrl);
      setIsIos("android");
    } else {
      let appUrl = "https://static.hntv.tv/weiboshare/";
      setAppUrl(appUrl);
      setIsIos("other");
    }
  }, [article]);

  return { isIos, appUrl };
};

function getQueryString(name) {
  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  let r = window.location.search.substr(1).match(reg);
  if (r != null) {
    return unescape(r[2]);
  }
  return null;
}

export default useWakeApp;
